<template>
  <div class="tag-list">
    <a-page-header
      title="标签管理"
      sub-title="管理系统中的标签，包括新增、编辑和删除等操作。"
    />
    <a-divider />
    <a-card class="search-card">
      <template #title>
        <span>搜索条件</span>
        <a-divider type="vertical" />
      </template>
      <a-form layout="inline">
        <a-form-item label="标签名称">
          <a-input v-model:value="searchForm.name" placeholder="请输入标签名称" allowClear />
        </a-form-item>
        <a-form-item label="状态">
          <a-select
            v-model:value="searchForm.status"
            placeholder="请选择状态"
            allowClear
            style="width: 150px"
          >
            <a-select-option :value="1">启用</a-select-option>
            <a-select-option :value="0">禁用</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">
              <template #icon><search-outlined /></template>查询
            </a-button>
            <a-button @click="resetSearch">
              <template #icon><reload-outlined /></template>重置
            </a-button>
            <a-button type="primary" @click="handleAdd" v-permission="'content:tag:add'">
                <template #icon><plus-outlined /></template>新增标签
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <a-table 
        bordered
        :columns="columns" 
        :data-source="tableData" 
        :loading="loading" 
        :pagination="{
            current: currentPage,
            pageSize: pageSize,
            total: total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`
        }"
        @change="handleTableChange"
        rowKey="id">
        <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
            <a-space>
                <a-button type="primary" @click="handleEdit(record)" v-permission="'content:tag:edit'">
                  <template #icon><edit-outlined /></template>编辑
                </a-button>
                <a-popconfirm
                title="确定要删除该标签吗？"
                @confirm="handleDelete(record.id)"
                ok-text="确定"
                cancel-text="取消"
                >
                <a-button type="primary" danger v-permission="'content:tag:delete'">
                  <template #icon><delete-outlined /></template>删除
                </a-button>
                </a-popconfirm>
            </a-space>
            </template>
            <template v-else-if="column.key === 'status'">
            <a-tag :color="record.status === 1 ? 'green' : 'red'">
                {{ record.status === 1 ? '启用' : '禁用' }}
            </a-tag>
            </template>
            <template v-else-if="column.key === 'description'">
              <span>{{ record.description || '-' }}</span>
            </template>
        </template>
    </a-table>

    <!-- 新增/编辑标签对话框 -->
    <a-modal
      :title="dialogTitle"
      :visible="dialogVisible"
      @ok="submitForm"
      @cancel="handleModalCancel"
      :confirmLoading="modalLoading"
    >
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item label="标签名称" name="name">
          <a-input v-model:value="form.name" placeholder="请输入标签名称" />
        </a-form-item>
        <a-form-item label="标签描述" name="description">
          <a-textarea v-model:value="form.description" placeholder="请输入标签描述" :rows="3" />
        </a-form-item>
        <a-form-item label="是否为导航标签" name="fixedNav">
          <a-radio-group v-model:value="form.fixedNav">
            <a-radio :value="1">是</a-radio>
            <a-radio :value="0">否</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="状态" name="status">
          <a-radio-group v-model:value="form.status">
            <a-radio :value="1">启用</a-radio>
            <a-radio :value="0">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, onMounted, toRefs } from 'vue';
import { message, PageHeader } from 'ant-design-vue';
import { SearchOutlined, ReloadOutlined, PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import axios from 'axios';

export default defineComponent({
  name: 'TagList',
  components: {
    SearchOutlined,
    ReloadOutlined,
    PlusOutlined,
    EditOutlined,
    DeleteOutlined,
    APageHeader: PageHeader,
  },
  setup() {
    const formRef = ref(null);
    const loading = ref(false);
    const tableData = ref([]);
    const total = ref(0);
    const currentPage = ref(1);
    const pageSize = ref(10);
    const dialogVisible = ref(false);
    const dialogTitle = ref('新增标签');
    const isEdit = ref(false);
    const modalLoading = ref(false);
    
    const searchForm = reactive({
      name: '',
      status: undefined,
    });
    
    const form = reactive({
      id: '',
      name: '',
      description: '',
      status: 1,
      fixedNav: 0,
    });
    
    const rules = {
      name: [
        { required: true, message: '请输入标签名称', trigger: 'blur' },
        { max: 50, message: '长度不能超过50个字符', trigger: 'blur' }
      ],
      status: [
        { required: true, message: '请选择状态', trigger: 'change' }
      ]
    };

    const columns = [
      {
        title: '序号',
        key: 'index',
        width: 80,
        customRender: ({ index }) => index + 1
      },
      {
        title: '标签名称',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: '标签描述',
        dataIndex: 'description',
        key: 'description',
      },
      {
        title: '使用次数',
        dataIndex: 'useCount',
        key: 'useCount',
        width: 100,
        customRender: ({ text }) => text || 0,
      },
      {
        title: '是否为导航标签',
        dataIndex: 'fixedNav',
        key: 'fixedNav',
        width: 100,
        customRender: ({ record }) => {
          return record.fixedNav === 1 ? '是' : '否';
        },
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        width: 100,
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
        width: 180,
      },
      {
        title: '操作',
        key: 'action',
        width: 200,
        fixed: 'right',
      }
    ];

    // 获取标签列表
    const getTagList = (page = currentPage.value, size = pageSize.value) => {
      loading.value = true;
      const params = {
        current: page,
        size: size,
        name: searchForm.name,
        status: searchForm.status
      };
      
      axios.get('/api/tag/page', { params })
        .then(response => {
          if (response.data.code === 200) {
            tableData.value = response.data.data.records;
            total.value = response.data.data.total;
            currentPage.value = page;
            pageSize.value = size;
          } else {
            message.error(response.data.message || '获取标签列表失败');
          }
        })
        .catch(error => {
          console.error('获取标签列表失败:', error);
          message.error('获取标签列表失败');
        })
        .finally(() => {
          loading.value = false;
        });
    };

    // 表格变化事件
    const handleTableChange = (pag) => {
      getTagList(pag.current, pag.pageSize);
    };

    // 搜索
    const handleSearch = () => {
      getTagList(1, pageSize.value);
    };

    // 重置搜索
    const resetSearch = () => {
      searchForm.name = '';
      searchForm.status = undefined;
      handleSearch();
    };

    // 新增标签
    const handleAdd = () => {
      dialogTitle.value = '新增标签';
      isEdit.value = false;
      form.id = '';
      form.name = '';
      form.description = '';
      form.status = 1;
      form.fixedNav = 0;
      dialogVisible.value = true;
    };

    // 编辑标签
    const handleEdit = (record) => {
      dialogTitle.value = '编辑标签';
      isEdit.value = true;
      form.id = record.id;
      form.name = record.name;
      form.description = record.description;
      form.status = record.status;
      form.fixedNav = record.fixedNav;
      dialogVisible.value = true;
    };

    // 删除标签
    const handleDelete = (id) => {
      axios.delete(`/api/tag/${id}`)
        .then(response => {
          if (response.data.code === 200) {
            message.success('删除成功');
            getTagList();
          } else {
            message.error(response.data.message || '删除失败');
          }
        })
        .catch(error => {
          console.error('删除失败:', error);
          message.error('删除失败');
        });
    };

    // 弹窗取消
    const handleModalCancel = () => {
      dialogVisible.value = false;
    };

    // 提交表单
    const submitForm = () => {
      formRef.value.validate().then(() => {
        modalLoading.value = true;
        
        if (isEdit.value) {
          // 编辑
          axios.put(`/api/tag/${form.id}`, form)
            .then(response => {
              if (response.data.code === 200) {
                message.success('更新成功');
                dialogVisible.value = false;
                getTagList();
              } else {
                message.error(response.data.message || '更新失败');
              }
            })
            .catch(error => {
              console.error('更新失败:', error);
              message.error('更新失败');
            })
            .finally(() => {
              modalLoading.value = false;
            });
        } else {
          // 新增
          axios.post('/api/tag', form)
            .then(response => {
              if (response.data.code === 200) {
                message.success('创建成功');
                dialogVisible.value = false;
                getTagList();
              } else {
                message.error(response.data.message || '创建失败');
              }
            })
            .catch(error => {
              console.error('创建失败:', error);
              message.error('创建失败');
            })
            .finally(() => {
              modalLoading.value = false;
            });
        }
      }).catch(error => {
        console.log('验证失败:', error);
      });
    };

    onMounted(() => {
      getTagList();
    });

    return {
      formRef,
      loading,
      tableData,
      total,
      currentPage,
      pageSize,
      dialogVisible,
      dialogTitle,
      isEdit,
      modalLoading,
      searchForm,
      form,
      rules,
      columns,
      getTagList,
      handleTableChange,
      handleSearch,
      resetSearch,
      handleAdd,
      handleEdit,
      handleDelete,
      handleModalCancel,
      submitForm
    };
  }
});
</script>

<style scoped>
.tag-list {
  background-color: transparent;
}

.search-card {
  margin-bottom: 20px;
}

.operation-bar {
  margin-bottom: 20px;
}
</style>